import axios from 'axios';
import { Message } from 'element-ui';
import Vue from 'vue'

/**
 *  axios 拦截
 */

// 请求拦截
axios.interceptors.request.use(config => {
    showFullScreenLoading();
    return config
}, error => {
    tryHideFullScreenLoading();
    return Promise.reject(error)
});

// 响应拦截
axios.interceptors.response.use(response => {
    tryHideFullScreenLoading();
    if (response.status != "200" || response.data == "error") {
        Message.error("系统出错，请联系管理员处理！");
    }
    // 请求成功
    // 1. 根据自己项目需求定制自己的拦截
    // 2. 然后返回数据
    return response;
}, error => {
    // 请求失败
    if (error && error.response) {
        tryHideFullScreenLoading();
        switch (error.response.status) {
            case 400:
                break
            case 401:
                break
            default:
                return Promise.reject(error);
        }
    }
});

/* ======================================================================加载层相关====================================================================== */
// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading;
function startLoading() {
    loading = Vue.prototype.$loading({
        lock: true,
        text: "Loading...",
        //设置加载动画区域 没设置则全屏
        target: document.querySelector(".loadarea")
    });
}
function endLoading() {
    loading.close();
}
//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading();
    }
    needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        endLoading();
    }
};
